package hk.edu.polyu.comp.motioncapture.dummycamera;

import java.util.*;
import java.io.*;
import java.net.*;

public class MotionCaptureDummyCamera {
	protected String filename;
	protected String host;
	protected int port;

	public static void main(String[] args) {
		MotionCaptureDummyCamera app = null;

		if (args.length == 0) {
			app = new MotionCaptureDummyCamera();
		} else if (args.length == 1) {
			app = new MotionCaptureDummyCamera(args[0], args[1], Integer
					.parseInt(args[2]));
		} else if (args.length == 2) {
			app = new MotionCaptureDummyCamera(args[0], args[1]);
		} else if (args.length == 3) {
			app = new MotionCaptureDummyCamera(args[0], args[1], Integer
					.parseInt(args[2]));
		} else {
			System.out.println("Usage: DummyInput file [ip [port]]");
			return;
		}

		app.run();
	}

	public MotionCaptureDummyCamera() {
		this("input.txt");
	}

	public MotionCaptureDummyCamera(String filename) {
		this(filename, "localhost");
	}

	public MotionCaptureDummyCamera(String filename, String host) {
		this(filename, host, 8000);
	}

	public MotionCaptureDummyCamera(String filename, String host, int port) {
		this.filename = filename;
		this.host = host;
		this.port = port;
	}

	public void run() {
		try {
			Scanner keyb = new Scanner(System.in).useDelimiter("\n");

			System.out.println("Press ENTER to connect to " + host + ":" + port
					+ " ...");
			keyb.next();

			Socket socket = new Socket(host, port);
			System.out.println("Connected");

			BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
					socket.getOutputStream()));

			String ln;
			System.out.println();

			while (true) {
				BufferedReader in = new BufferedReader(new FileReader(new File(
						filename)));

				while (in.ready()) {
					ln = in.readLine();
					out.write(ln + "\n");
					out.flush();

					// System.out.println("Wrote: " + ln);
					try {
						Thread.sleep(20);
					} catch (InterruptedException ex) {
						ex.printStackTrace();
					}
				}

				in.close();
			}
			// System.out.println("End");

		} catch (UnknownHostException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}
